package spacecrack;

import spacecrack.UnitManager.Target;
import spacecrack.UnitManager.Unit;

public class MapGenerator {
	int maxj, maxi;
	Unit[][] units;

	public MapGenerator(int maxi, int maxj) {
		this.maxj = maxi;
		this.maxi = maxj;
	}

	public void generate(UnitManager um) {
		this.units = new Unit[maxj][maxi];

		generateUnits();
		generateTargets();

		for (int j = 0; j < maxj; ++j) {
			for (int i = 0; i < maxi; ++i) {
				final Unit unit = units[i][j];
				if (unit == null) continue;
				um.addUnit(unit);
			}
		}

		this.units = null;
	}

	private void generateUnits() {
		int n = 1;
		for (int j = 0; j < maxj; ++j) {
			for (int i = 0; i < maxi; ++i) {
				boolean even = (j%2 != 0);
				if (even && i == 0) continue;

				final String id = "u"+ n++;
				final String name = "Name"+ n;
				final int uPosx = 384*i - (even ? 192 : 0);
				final int uPosy = 192*j;
				final int uShips = (int)(Math.random() * 20);
				final Unit unit = new Unit(id, name, uPosx, uPosy, uShips);

				units[i][j] = unit;
			}
		}
	}

	private void generateTargets() {
		for (int uj = 0; uj < maxj; ++uj) {
		for (int ui = 0; ui < maxi; ++ui) {
			final Unit u = units[ui][uj];
			if (u == null) continue;
		for (int i = -1; i <= 1; ++i) {
			for (int j = -1; j <= 1; ++j) {
				int ti = ui + i;
				int tj = ui + j;

				if (ti < 0 || ti >= maxj) continue;
				if (tj < 0 || tj >= maxi) continue;

				final Unit t = units[ti][tj];
				if (t == null) continue;
				if (u == t) continue;

				int dx = t.getPosX() - u.getPosX();
				int dy = t.getPosY() - u.getPosY();

				String id = t.getId();
				int tPosx = dx/2;
				int tPosy = dy/2;

				final Target target = new Target(id, tPosx, tPosy);
				units[ui][uj].addTarget(target);
			}
		}
		}
		}
	}
}
